package b2.scene.camp
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.base.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.fort.*;
	
	import flash.display.*;
	import flash.events.*;
	
	public class CampScene extends BasicScene
	{
		public var fortressList:Object;
		public var bottomBar:BottomBar;
		
		static private var instance:CampScene;

		public function CampScene()
		{
			super();
			var fortLayer:Sprite = new Sprite();
			addChild(fortLayer);
			//加载背景
			var CampBgr:Class = ResourceHelper.getInstance().getClassByName("CampBgr");
			var campBgr:Sprite = new CampBgr();
			campBgr.x = -20;
			fortLayer.addChild(campBgr);
			//加载要塞
			fortressList = new Object();
			for (var fortIndex:String in Config.fortressConfigs)
			{
				var fortressConfig:FortressConfig = Config.fortressConfigs[fortIndex];
				var fortress:Fortress = new Fortress(fortressConfig.index, (fortressConfig.index == 5) || (fortressConfig.index == 1) 
					|| (fortressConfig.index == 6) || (fortressConfig.index == 8));
				fortress.x = fortressConfig.iconPosX - 20;
				fortress.y = fortressConfig.iconPosY;
				fortLayer.addChild(fortress);
				fortressList[fortIndex] = fortress;
			}
			//加载右上角图标
			var topBar:TopBar = new TopBar();
			addChild(topBar);
			//加载底部图标
			bottomBar = new BottomBar();
			addChild(bottomBar);
			//返回基地按钮
			var BaseIcon:Class = ResourceHelper.getInstance().getClassByName("BaseIcon");
			var baseIcon:BasicIcon = new BasicIcon(BaseIcon, "返回基地", 0, true);
			baseIcon.x = 160;
			baseIcon.y = BFont.stageHeight - 75;
			addChild(baseIcon);
			baseIcon.addEventListener(MouseEvent.CLICK, onBaseIconClick);
			//监听经验变动
			ServerHelper.getInstance().addEventListener(ServerEvent.END_FIGHT, onRefreshExp);
			ServerHelper.getInstance().addEventListener(ServerEvent.FETCH_GIFT, onRefreshExp);
			ServerHelper.getInstance().addEventListener(ServerEvent.ACCOMP_TASK, onRefreshExp);
		}

		static public function getInstance():CampScene
		{
			if (!instance)
				instance = new CampScene();
			return instance;
		}
		
		private function onRefreshExp(event:ServerEvent):void
		{
			for (var fortIndex:String in fortressList)
			{
				var fortress:Fortress = fortressList[fortIndex];
				var oldAbleToGo:Boolean = fortress.isAbleToGo();
				fortress.refresh();
				if (!oldAbleToGo && fortress.isAbleToGo())
				{
					var fortressConfig:FortressConfig = Config.fortressConfigs[fortIndex];
					ServerHelper.sendFeed("开启了新的篇章——" + fortressConfig.name); 
				}
			}
		}
		
		private function onBaseIconClick(event:MouseEvent):void
		{
			if (SceneManager.getInstance().currentScene is BaseScene)
			{
				SceneManager.getInstance().loadScene(CampScene.getInstance());
			}
			else if (SceneManager.getInstance().currentScene is CampScene)
			{
				SceneManager.getInstance().loadScene(BaseScene.getInstance());
			}
		}
	}
}